package com.ifd.iview.controller.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.zkoss.zk.ui.Execution;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.util.Composer;
import org.zkoss.zk.ui.util.GenericForwardComposer;
import org.zkoss.zk.ui.util.Initiator;
import org.zkoss.zul.Button;
import org.zkoss.zul.Textbox;

import com.ifd.iview.controller.AuthorizedZkPage;
import com.ifd.iview.model.UserManager;
import com.ifd.iview.model.UserManagerFactory;
import com.ifd.iview.model.UserVO;
import com.ifd.iview.utils.IviewUtils;


public class LoginController extends GenericForwardComposer implements Composer {
	@Wire
	private Textbox usernameTbx;

	@Wire
	private Textbox passwordTbx;
	
	@Wire
	private Button loginBtn;
	
	Logger logger = Logger.getLogger(LoginController.class);
	public void onClick$loginBtn(){
		Subject subj = SecurityUtils.getSubject();
		String username = usernameTbx.getValue().trim();
		String password = passwordTbx.getValue().trim(); 
		UsernamePasswordToken token = new UsernamePasswordToken(
				username, password);
		token.setRememberMe(true);
		try {
			subj.login(token);
			Session session = subj.getSession();
			UserManager manager = UserManagerFactory.getUserManager();
			UserVO user = manager.findBy(username);
			session.setAttribute("user", user);
			String reqUri = (String)session.getAttribute("requestURI");
			if(reqUri==null)
				reqUri = IviewUtils.getResourceURI("/pages/main.zul");
			IviewUtils.sendRedirect(reqUri);
		} catch (Exception e) {
			logger.error("User " + username + " not found", e);
			e.printStackTrace();
		}
	}
}

	